<?php
	require("./library/random_AI.php");
	$random_AI = new Random_AI();
	
	$database_path = "sqlite:./db/data.sqlite";
	$time_out = 10;
	$dbh = NULL;
	$place_left = 42;
	$room_id = 1;
	
	$continent_bonus = array();
	$continent_bonus['Azio'] = 7;
	$continent_bonus['Ameroki'] = 6;
	$continent_bonus['Uiropa'] = 6;
	$continent_bonus['Afroki'] = 5;
	$continent_bonus['Amerpolu'] = 3;
	$continent_bonus['Uistralia'] = 3;
	
	$continent_land_count = array();
	$continent_land_count['Azio'] = 12;
	$continent_land_count['Ameroki'] = 9;
	$continent_land_count['Uiropa'] = 7;
	$continent_land_count['Afroki'] = 6;
	$continent_land_count['Amerpolu'] = 4;
	$continent_land_count['Uistralia'] = 4;
	
	$continents = array();
	$continents['Azio'] = array("Siberia", "Irkutsk", "Yakutsk", "Mongolia", "Middle_East", "China", "Ural", "Siam", "Afghanistan", "Kamchatka", "India", "Japan");
	$continents['Ameroki'] = array("Northwest_Territory", "Western_United_States", "Eastern_United_States", "Alaska", "Central_America", "Alberta", "Greenland", "Ontario", "Quebec");
	$continents['Uiropa'] = array("Ukraine", "Iceland", "Western_Europe", "Scandinavia", "Great_Britain", "Southern_Europe", "Northern_Europe");
	$continents['Afroki'] = array("Egypt", "North_Africa", "East_Africa", "Madagascar", "Congo", "South_Africa");
	$continents['Amerpolu'] = array("Argentina", "Venezuela", "Peru", "Brazil");
	$continents['Uistralia'] = array("Indonesia", "New_Guinea", "Western_Australia", "Eastern_Australia");
	
	header("Content-type: text/plain");
	
	function get_neighbour_toponyms($source, $link_info_file = "./map/default_small/link_info.txt") {
		$source = str_replace("_", " ", $source);
		$result_array = array();
		$fh = fopen($link_info_file, 'r');
		
		while (!feof($fh)) {
			$line = fgets($fh);
			if (strpos($line, stristr(trim($line), trim($source))) === 0) {
				$token = strtok($line, ",>");
				$count = 0;
				while ($token !== false) {
					if ($count > 0) {	// Skip the first one(source)
						$result_array[$count - 1] = str_replace(" ", "_", trim($token));
					}
					$token = strtok(",>");
					$count++;
				}
				break;
			}
		}
		fclose($fh);
		return $result_array;
	}
	
	function respond_regular_info($database_path, $comment) {
		try {
			$dbh = new PDO($database_path);
			// Regular info (user and map status)
			$respond = array();
			
			$get_user_info = $dbh->prepare("SELECT session.*, game_room.status FROM session, game_room WHERE session.room_id = game_room.room_id");
			$get_user_info->execute();
			$user_info = $get_user_info->fetchAll(PDO::FETCH_ASSOC);
			$get_user_info->closeCursor();
			
			//print_r($user_info);
			foreach($user_info as &$player) {
				$player_session = $player['session_key'];
				
				$get_player_cards = $dbh->prepare("SELECT * FROM card_status WHERE owner=$player_session");
				$get_player_cards->execute();
				$cards_info = $get_player_cards->fetchAll(PDO::FETCH_ASSOC);
				$get_player_cards->closeCursor();
				
				$player['cards'] = $cards_info;
			}
			//print_r($user_info);
			
			$get_map_status = $dbh->prepare("SELECT * FROM map_status");
			$get_map_status->execute();
			$map_status = $get_map_status->fetchAll(PDO::FETCH_ASSOC);
			$get_map_status->closeCursor();
			
			$respond['user_info'] = $user_info;
			$respond['map_status'] = $map_status;
			$respond['comments'] = $comment;
			
			return $respond;
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function get_current_turn_player_session($database_path) {
		$dbh = new PDO($database_path);
		$get_current_turn_player = $dbh->prepare("SELECT session_key FROM session WHERE turn=1");
		$get_current_turn_player->execute();
		$result = $get_current_turn_player->fetch(PDO::FETCH_ASSOC);
		$current_turn_player_session_key = $result['session_key'];
		$get_current_turn_player->closeCursor();
		
		return $current_turn_player_session_key;
	}
	
	function get_current_turn_player_turn_seq($database_path) {
		$dbh = new PDO($database_path);
		$get_current_turn_player = $dbh->prepare("SELECT turn_seq FROM session WHERE turn=1");
		$get_current_turn_player->execute();
		$result = $get_current_turn_player->fetch(PDO::FETCH_ASSOC);
		$current_turn_player_turn_seq = $result['turn_seq'];
		$get_current_turn_player->closeCursor();
		
		return $current_turn_player_turn_seq;
	}
	
	function init_game($database_path, $place_left) {
		try {
			$dbh = new PDO($database_path);
			
			global $room_id;
			$start_game = $dbh->prepare("UPDATE game_room SET status='START', backup_round=1 WHERE room_id=$room_id");
			$start_game->execute();
			$start_game->closeCursor();
			
			// Randomly assign the first player
			$number_of_players = $dbh->prepare("SELECT COUNT(DISTINCT session_key) FROM session");
			$number_of_players->execute();
			$result = $number_of_players->fetchAll();
			$max_players = $result[0][0];
			$number_of_players->closeCursor();
			
			$first_player = rand(0, $max_players-1);
			$first_player_session = $dbh->prepare("SELECT session_key FROM session LIMIT 1 OFFSET " . $first_player);
			$first_player_session->execute();
			$result = $first_player_session->fetch(PDO::FETCH_ASSOC);
			$first_player_session_key = $result['session_key'];
			$first_player_session->closeCursor();
			
			$default_troops = 0;
			if ($max_players == 6) {
				$default_troops = 20;
			}
			else if ($max_players == 6) {
				$default_troops = 20;
			}
			else if ($max_players == 5) {
				$default_troops = 25;
			}
			else if ($max_players == 4) {
				$default_troops = 30;
			}
			else if ($max_players == 3) {
				$default_troops = 35;
			}
			else if ($max_players == 2) {
				$default_troops = 40;
			}
			
			$update_turn = $dbh->prepare("UPDATE session SET card_number=0, watch_battle_flag=0, refill_troops=0, troops=$default_troops, troops_left=$default_troops, turn=1, turn_seq=1 WHERE session_key=" . $first_player_session_key);
			$update_turn->execute();
			$update_turn->closeCursor();
			
			for ($i = 1; $i < $max_players; $i++) {
				$player_session = $dbh->prepare("SELECT session_key FROM session LIMIT 1 OFFSET " . (($i + $first_player) % $max_players));
				$player_session->execute();
				$result = $player_session->fetch(PDO::FETCH_ASSOC);
				$player_session_key = $result['session_key'];
				$player_session->closeCursor();
				
				$update_turn = $dbh->prepare("UPDATE session SET card_number=0, watch_battle_flag=0, refill_troops=0, troops=$default_troops, troops_left=$default_troops, turn=0, turn_seq=". ($i + 1) ." WHERE session_key=" . $player_session_key);
				$update_turn->execute();
				$update_turn->closeCursor();
			}
			
			$update_to_deployment_status = $dbh->prepare("UPDATE game_room SET status='DEPLOYMENT', place_left=$place_left WHERE room_id=$room_id");
			$update_to_deployment_status->execute();
			$update_to_deployment_status->closeCursor();
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function get_current_turn_player_refill_troops($database_path) {
		try {
			$dbh = new PDO($database_path);
			
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			$total_refill_troops = 0;
			
			// Basic troops
			$get_number_of_land = $dbh->prepare("SELECT COUNT(DISTINCT toponym) FROM map_status WHERE owner=$current_turn_player_session_key");
			$get_number_of_land->execute();
			$result = $get_number_of_land->fetch(PDO::FETCH_ASSOC);
			$number_of_land = $result['COUNT(DISTINCT toponym)'];
			$get_number_of_land->closeCursor();
			
			(int)$basic_troops = (int)($number_of_land / 3);
			
			if ($basic_troops < 3) {
				$basic_troops = 3;
			}
			
			$total_refill_troops += $basic_troops;
			
			// Continental troops
			global $continent_land_count;
			global $continent_bonus;
			$continent_keys = array();
			$continent_keys = array_keys($continent_land_count);
			foreach ($continent_keys as $continent) {
				$get_number_of_land = $dbh->prepare("SELECT COUNT(DISTINCT toponym) FROM map_status WHERE owner=$current_turn_player_session_key AND continent='$continent'");
				$get_number_of_land->execute();
				$result = $get_number_of_land->fetch(PDO::FETCH_ASSOC);
				$number_of_land = $result['COUNT(DISTINCT toponym)'];
				$get_number_of_land->closeCursor();
				
				// This player own a continent
				if ($continent_land_count[$continent] == $number_of_land) {
					$total_refill_troops += $continent_bonus[$continent];
				}
			}
			
			return $total_refill_troops;
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function update_to_next_player_turn($database_path) {
		try {
			$dbh = new PDO($database_path);
			
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			$current_turn_player_turn_seq = get_current_turn_player_turn_seq($database_path);
			
			$number_of_players = $dbh->prepare("SELECT COUNT(DISTINCT session_key) FROM session");
			$number_of_players->execute();
			$result = $number_of_players->fetchAll();
			$max_players = $result[0][0];
			$number_of_players->closeCursor();
			
			$set_current_player_turn_to_zero = $dbh->prepare("UPDATE session SET turn=0 WHERE session_key=" . $current_turn_player_session_key);
			$set_current_player_turn_to_zero->execute();
			$set_current_player_turn_to_zero->closeCursor();
			
			$get_next_player = $dbh->prepare("SELECT MIN(turn_seq) FROM session WHERE turn_seq>$current_turn_player_turn_seq");
			$bool = $get_next_player->execute();
			$result = $get_next_player->fetch(PDO::FETCH_ASSOC);
			$next_player = $result['MIN(turn_seq)'];
			$get_next_player->closeCursor();
			if ($next_player == NULL) {
				$get_first_player = $dbh->prepare("SELECT turn_seq FROM session WHERE NOT turn_seq=-1 ORDER BY turn_seq ASC");
				$get_first_player->execute();
				$result = $get_first_player->fetch(PDO::FETCH_ASSOC);
				$first_player = $result['turn_seq'];
				$next_player = $first_player;
				$get_first_player->closeCursor;
			}
			
			$update_turn = $dbh->prepare("UPDATE session SET turn=1 WHERE turn_seq=" . $next_player);
			$update_turn->execute();
			$update_turn->closeCursor();
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function check_using_card($database_path) {
		global $room_id;
		try {
			$dbh = new PDO($database_path);
			
			$backup_troops = 0;
			
			
			if ($_GET['use_card'] == "1" && $_GET['card_1'] != '' && $_GET['card_2'] != '' && $_GET['card_3'] != '' && $_GET['card_1_type'] != '' && $_GET['card_2_type'] != '' && $_GET['card_3_type'] != '') {
				if ($_GET['card_1_type'] == $_GET['card_2_type'] && $_GET['card_1_type'] == $_GET['card_3_type']
					||
					$_GET['card_1_type'] != $_GET['card_2_type'] && $_GET['card_2_type'] != $_GET['card_3_type'] && $_GET['card_3_type'] != $_GET['card_1_type']) {
					$card_1 = $_GET['card_1'];
					$card_2 = $_GET['card_2'];
					$card_3 = $_GET['card_3'];
					$card_1_type = $_GET['card_1_type'];
					$card_2_type = $_GET['card_2_type'];
					$card_3_type = $_GET['card_3_type'];
					
					// Check card ownership and existence
					$check_ownership_1 = $dbh->prepare("SELECT owner FROM card_status WHERE toponym='$card_1' AND troop_type='$card_1_type'");
					$check_ownership_1->execute();
					$result = $check_ownership_1->fetch(PDO::FETCH_ASSOC);
					$ownership_1 = $result['owner'];
					$check_ownership_1->closeCursor();
					
					$check_ownership_2 = $dbh->prepare("SELECT owner FROM card_status WHERE toponym='$card_2' AND troop_type='$card_2_type'");
					$check_ownership_2->execute();
					$result = $check_ownership_2->fetch(PDO::FETCH_ASSOC);
					$ownership_2 = $result['owner'];
					$check_ownership_2->closeCursor();
					
					$check_ownership_3 = $dbh->prepare("SELECT owner FROM card_status WHERE toponym='$card_3' AND troop_type='$card_3_type'");
					$check_ownership_3->execute();
					$result = $check_ownership_3->fetch(PDO::FETCH_ASSOC);
					$ownership_3 = $result['owner'];
					$check_ownership_3->closeCursor();
					
					if ($ownership_1 != '' && $ownership_1 == $ownership_2 && $ownership_1 == $ownership_3) {
						// Add extra troops
						$get_backup_round = $dbh->prepare("SELECT backup_round FROM game_room WHERE room_id=$room_id");
						$get_backup_round->execute();
						$result = $get_backup_round->fetch(PDO::FETCH_ASSOC);
						$backup_round = $result['backup_round'];
						$get_backup_round->closeCursor();
						
						$backup_troops = ((int)$backup_round + 2) * 5;
						if ($backup_troops > 60)
							$backup_troops = 60;
						
						// Update backup round
						$backup_round += 1;
						$set_backup_round = $dbh->prepare("UPDATE game_room SET backup_round=$backup_round");
						$set_backup_round->execute();
						$set_backup_round->closeCursor();
						
						// Check extra unit
						$check_extra_1 = $dbh->prepare("SELECT * FROM map_status WHERE owner==$ownership_1 AND toponym='$card_1'");
						$check_extra_1->execute();
						$result = $check_extra_1->fetchAll();
						$check_extra_1->closeCursor();	
						
						if ($result != "") {
							reinforcement_for_current_player($database_path, 2, $card_1);
						}
						
						$check_extra_2 = $dbh->prepare("SELECT * FROM map_status WHERE owner==$ownership_2 AND toponym='$card_3'");
						$check_extra_2->execute();
						$result = $check_extra_2->fetchAll();
						$check_extra_2->closeCursor();	
						
						if ($result != "") {
							reinforcement_for_current_player($database_path, 2, $card_2);
						}
						
						$check_extra_3 = $dbh->prepare("SELECT * FROM map_status WHERE owner==$ownership_3 AND toponym='$card_3'");
						$check_extra_3->execute();
						$result = $check_extra_3->fetchAll();
						$check_extra_3->closeCursor();	
						
						if ($result != "") {
							reinforcement_for_current_player($database_path, 2, $card_3); 
						}
						
						// Remove cards from database
						$remove_card_1 = $dbh->prepare("DELETE FROM card_status WHERE toponym='$card_1' AND troop_type='$card_1_type' AND owner=$ownership_1");
						$remove_card_1->execute();
						$remove_card_1->closeCursor();
						
						$remove_card_2 = $dbh->prepare("DELETE FROM card_status WHERE toponym='$card_2' AND troop_type='$card_2_type' AND owner=$ownership_2");
						$remove_card_2->execute();
						$remove_card_2->closeCursor();
						
						$remove_card_3 = $dbh->prepare("DELETE FROM card_status WHERE toponym='$card_3' AND troop_type='$card_3_type' AND owner=$ownership_3");
						$remove_card_3->execute();
						$remove_card_3->closeCursor();
						
						$get_owner_card_number = $dbh->prepare("SELECT card_number FROM session WHERE session_key=$ownership_1");
						$get_owner_card_number->execute();
						$result = $get_owner_card_number->fetch(PDO::FETCH_ASSOC);
						$card_number = $result['card_number'];
						$get_owner_card_number->closeCursor();
						
						$card_number -= 3;
						
						$update_card_number = $dbh->prepare("UPDATE session SET card_number=$card_number WHERE session_key=$ownership_1");
						$update_card_number->execute();
						$update_card_number->closeCursor();
					}
				}
			}
			
			return $backup_troops;
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
		
	}
	
	function update_troops_number($database_path, $troops_unit) {
		try {
			$dbh = new PDO($database_path);
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			$get_troops = $dbh->prepare("SELECT troops, troops_left FROM session WHERE session_key=$current_turn_player_session_key");
			$get_troops->execute();
			$result = $get_troops->fetch(PDO::FETCH_ASSOC);
			$total_troops = $result['troops'];
			$total_troops_left = $result['troops_left'];
			$get_troops->closeCursor();
			
			$total_troops += $troops_unit;
			$total_troops_left += $troops_unit;
			
			$set_troops = $dbh->prepare("UPDATE session SET troops=$total_troops, troops_left=$total_troops_left WHERE session_key=$current_turn_player_session_key");
			$bool = $set_troops->execute();
			$set_troops->closeCursor();
		}  catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function refill_troops_for_current_player($database_path) {
		try {
			$dbh = new PDO($database_path);
			
			$total_refill_troops = 0;
			
			// Calculate refill troops
			$total_refill_troops += get_current_turn_player_refill_troops($database_path);
			
			// Check if user would like to use backup troops
			//$total_refill_troops += check_using_card($database_path);
			
			// Update the number of refill troops
			update_troops_number($database_path, $total_refill_troops);
			
			return $total_refill_troops;
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function reinforcement_for_current_player($database_path, $troops_unit, $toponym) {
		try {
			$dbh = new PDO($database_path);
			
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			$get_troops_left = $dbh->prepare("SELECT troops_left FROM session WHERE session_key=$current_turn_player_session_key");
			$get_troops_left->execute();
			$result = $get_troops_left->fetch(PDO::FETCH_ASSOC);
			$troops_left = $result['troops_left'];
			$get_troops_left->closeCursor();
			
			if ((int)$troops_left > 0) {
				// Subtract troops left for reinforcement
				$troops_left -= $troops_unit;
				if ($troops_left < 0) {
					$troops_unit += $troops_left;
					$troops_left = 0;
				}
				$update_troops_left = $dbh->prepare("UPDATE session SET troops_left=$troops_left WHERE session_key=$current_turn_player_session_key;");
				$update_troops_left->execute();
				$update_troops_left->closeCursor();
				
				// Reinforce selected toponym
				$get_troops_number = $dbh->prepare("SELECT troops FROM map_status WHERE toponym='$toponym'");
				$get_troops_number->execute();
				$result = $get_troops_number->fetch(PDO::FETCH_ASSOC);
				$troops_number = $result["troops"];
				$troops_number += $troops_unit;
				$get_troops_number->closeCursor();
				
				$update_troops_number = $dbh->prepare("UPDATE map_status SET troops=$troops_number WHERE toponym='$toponym'");
				$update_troops_number->execute();
				$update_troops_number->closeCursor();
			}
		} catch (PDOException $e) {
			echo $e->getMessage();
		}	
	}
	
	function mobilize($database_path, $mobilize_from, $mobilize_to, $unit) {
		try {
			$dbh = new PDO($database_path);
			
			
			$from = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$mobilize_from'");
			$from->execute();
			$result = $from->fetch(PDO::FETCH_ASSOC);
			$from_owner = $result['owner'];
			$from->closeCursor();
			
			$to = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$mobilize_to'");
			$to->execute();
			$result = $to->fetch(PDO::FETCH_ASSOC);
			$to_owner = $result['owner'];
			$to->closeCursor();
			
			$array_of_neighbour = get_neighbour_toponyms($mobilize_from);
			$neighbour_flag = 0;
			foreach ($array_of_neighbour as $neighbour) {
				if ($neighbour == $mobilize_to) {
					$neighbour_flag = 1;
				}
			}

			if ($from_owner == $to_owner && $neighbour_flag == 1) {
				
				$get_from_troops = $dbh->prepare("SELECT troops FROM map_status WHERE toponym='$mobilize_from'");
				$get_from_troops->execute();
				$result = $get_from_troops->fetch(PDO::FETCH_ASSOC);
				$from_troops = $result['troops'];
				$get_from_troops->closeCursor();
				
				$get_to_troops = $dbh->prepare("SELECT troops FROM map_status WHERE toponym='$mobilize_to'");
				$get_to_troops->execute();
				$result = $get_to_troops->fetch(PDO::FETCH_ASSOC);
				$to_troops = $result['troops'];
				$get_to_troops->closeCursor();
				
				if ($from_troops > 1) {
					(int)$from_troops -= (int)$unit;
					(int)$to_troops += (int)$unit;

					$update_from = $dbh->prepare("UPDATE map_status SET troops=$from_troops WHERE toponym='$mobilize_from'");
					$update_from->execute();
					$update_from->closeCursor();
					
					$update_to = $dbh->prepare("UPDATE map_status SET troops=$to_troops WHERE toponym='$mobilize_to'");
					$update_to->execute();
					$update_to->closeCursor();
				}
			}
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function gain_one_card($database_path, $session_key, $continents) {
		try {
			$dbh = new PDO($database_path);
			
			$get_card_number = $dbh->prepare("SELECT card_number FROM session WHERE session_key=$session_key");
			$get_card_number->execute();
			$result = $get_card_number->fetch(PDO::FETCH_ASSOC);
			$card_number = $result['card_number'];
			$get_card_number->closeCursor();
			
			$card_number += 1;
			
			$add_one_card = $dbh->prepare("UPDATE session SET card_number=$card_number WHERE session_key=$session_key");
			$add_one_card->execute();
			$add_one_card->closeCursor();
			
			$rand_troop_type;
			$rand_toponym;
			
			$duplicate_flag = 1;
			do {
				$keys = array_keys($continents);
				$rand_key_index = rand(0,count($keys) - 1);
				$rand_key = $keys[$rand_key_index];
				
				$rand_toponym_index = rand(0, count($continents[$rand_key])-1);
				$rand_toponym = $continents[$rand_key][$rand_toponym_index];
				
				$rand_troop_type_index = rand(0,2);
				$rand_troop_type;
				if($rand_troop_type_index == 0) {
					$rand_troop_type = "Infantry";
				}
				else if ($rand_troop_type_index == 1) {
					$rand_troop_type = "Cavalry";
				}
				else {
					$rand_troop_type = "Artillery";
				}
				
				$get_duplicate_count = $dbh->prepare("SELECT COUNT(*) FROM card_status WHERE owner=$session_key AND toponym='$rand_toponym' AND troop_type='$rand_troop_type'");
				$get_duplicate_count->execute();
				$result = $get_duplicate_count->fetch(PDO::FETCH_ASSOC);
				$duplicate_count = $result['COUNT(*)'];
				$get_duplicate_count->closeCursor();
				
				if ($duplicate_count == 0)
					$duplicate_flag = 0;
				
			} while ($duplicate_flag == 1);
			
			$insert_card = $dbh->prepare("INSERT INTO card_status VALUES($session_key, '$rand_toponym', '$rand_troop_type')");
			$insert_card->execute();
			$insert_card->closeCursor();
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function get_AI_flag($database_path, $session_key) {
		try {
			$dbh = new PDO($database_path);
			
			$get_AI_flag = $dbh->prepare("SELECT ai_flag FROM session WHERE session_key=$session_key");
			$get_AI_flag->execute();
			$result = $get_AI_flag->fetch(PDO::FETCH_ASSOC);
			$AI_flag = $result['ai_flag'];
			$get_AI_flag->closeCursor();
			
			return $AI_flag;
		} catch (PDOException $e) {
			echo $e->getMessage();
		}	
	}
	
	function get_cards($database_path, $session_key = '') {
		try {
			$dbh = new PDO($database_path);
			
			// Retrieve card for specified user
			if ($session_key != '') {
				$get_user_cards = $dbh->prepare("SELECT * FROM card_status WHERE owner=$session_key");
			}
			else
				$get_user_cards = $dbh->prepare("SELECT * FROM card_status");
			
			$get_user_cards->execute();
			$result = $get_user_cards->fetchAll();
			$get_user_cards->closeCursor();
			
			return $result;
		} catch (PDOException $e) {
			echo $e->getMessage();
		}
	}
	
	function wrap_up($database_path) {
		try {
			$dbh = new PDO($database_path);
			// Delete all map status
			$delete_map_status = $dbh->prepare("DELETE FROM map_status");
			$delete_map_status->execute();
			$delete_map_status->closeCursor();
			
			$delete_card_status = $dbh->prepare("DELETE FROM card_status");
			$delete_card_status->execute();
			$delete_card_status->closeCursor();
		} catch (PDOException $e) {
			echo $e->getMessage();
		}	
	}
	
	/************************** Logic goes here **************************/
	try {
		$dbh = new PDO($database_path);
		
		// Checking dead player constantly
		$update_last_respond = $dbh->prepare("UPDATE session SET last_respond=" . time() . " WHERE session_key=" . $_COOKIE["session_key"]);
		$update_last_respond->execute();
		$update_last_respond->closeCursor();
		
		$get_all_sessions = $dbh->prepare("SELECT * FROM session WHERE NOT ai_flag=1");
		$get_all_sessions->execute();
		$result = $get_all_sessions->fetchAll();
		$current_time = time();
		foreach ($result as $row) {
			if ($current_time - (int)$row['last_respond'] > $time_out) {
				// A user time out
				// Make up with AI
				/*$update_last_respond = $dbh->prepare("UPDATE session SET ai_flag=1 WHERE session_key=" . $row['session']);
				$update_last_respond->execute();
				$update_last_respond->closeCursor();*/
			}
		}
		$get_all_sessions->closeCursor();
		
		$get_game_status = $dbh->prepare("SELECT status FROM game_room WHERE room_id=$room_id");
		$get_game_status->execute();
		$game_status = $get_game_status->fetch(PDO::FETCH_ASSOC);
		$get_game_status->closeCursor();
		// End checking
		
		if ($_GET['getCards'] == "1") {
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			if ($_GET['user'] != '')
				$cards_array = get_cards($database_path, $current_turn_player_session_key);
			else
				$cards_array = get_cards($database_path);
			
			echo json_encode($cards_array);
			exit;
		}
		
		// Waiting all user ready
		if ($game_status['status'] == 'START') {
			if ($_GET['status'] == "ready") {
				$update_player_ready = $dbh->prepare("UPDATE session SET ready=1 WHERE session_key=" . $_COOKIE['session_key']);
				$update_player_ready->execute();
				$update_player_ready->closeCursor();
				
				$get_not_ready_player = $dbh->prepare("SELECT COUNT(*) FROM session WHERE ready=0");
				$get_not_ready_player->execute();
				$result = $get_not_ready_player->fetch(PDO::FETCH_ASSOC);
				$not_ready_player = $result['COUNT(*)'];
				$get_not_ready_player->closeCursor();
				
				if ($not_ready_player == 0) {
					// Start Game
					init_game($database_path, $place_left);
				}
			}
			
			$respond = respond_regular_info($database_path, "WAITING ALL PLAYER START - status=ready");
			echo json_encode($respond);
		}
		
		// During Deployment status
		if ($game_status['status'] == "DEPLOYMENT") {
			
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			// Check if AI flag turn on
			$AI_flag = get_AI_flag($database_path, $current_turn_player_session_key);
			
			if ($_COOKIE["session_key"] == $current_turn_player_session_key || $AI_flag != "0") {
				if ($_GET["deploy_on"] != '' || $AI_flag != "0") {
					// The current turn player would like to get a land
					if ($AI_flag != "0") {
						if ($AI_flag == "1")
							$toponym = $random_AI->deployment($current_turn_player_session_key, $continents);
					}
					else
						$toponym = $_GET["deploy_on"];
					
					// Check if that place is already own by someone else
					$check_ownership = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$toponym'");
					$check_ownership->execute();
					$result = $check_ownership->fetch(PDO::FETCH_ASSOC);
					$ownership = $result['owner'];
					$check_ownership->closeCursor();
					
					if ($ownership == '') {
						foreach($continents as $key => $continent) {
							foreach($continent as $_toponym) {
								if($toponym == $_toponym) {
									$selected_continent = $key;
								}
							}
						}
						$require_a_place = $dbh->prepare("INSERT INTO map_status VALUES('$toponym', '$selected_continent', " . $current_turn_player_session_key . "," . "1, 0, 0)");
						$require_a_place->execute();
						$require_a_place->closeCursor();
						
						
						// Update place left
						$get_place_left = $dbh->prepare("SELECT place_left FROM game_room WHERE room_id=$room_id");
						$get_place_left->execute();
						$result = $get_place_left->fetch(PDO::FETCH_ASSOC);
						$place_left = $result['place_left'];
						$get_place_left->closeCursor();
						
						$place_left = (int)$place_left - 1;
						$update_place_left = $dbh->prepare("UPDATE game_room SET place_left=$place_left WHERE room_id=$room_id");
						$update_place_left->execute();
						$update_place_left->closeCursor();
						
						$get_troops_left = $dbh->prepare("SELECT troops_left FROM session WHERE session_key=". $current_turn_player_session_key);
						$get_troops_left->execute();
						$result = $get_troops_left->fetch(PDO::FETCH_ASSOC);
						$troops_left = $result['troops_left'];
						$troops_left -= 1;
						$get_troops_left->closeCursor();
						
						$update_troops_left = $dbh->prepare("UPDATE session SET troops_left=$troops_left WHERE session_key=" . $current_turn_player_session_key);
						$update_troops_left->execute();
						$update_troops_left->closeCursor();
						
						// Update to next player turn
						update_to_next_player_turn($database_path);
						
						if ($place_left <= 0) {
							// No place left, update the game status
							$enter_game_loop = $dbh->prepare("UPDATE game_room SET status='POST_DEPLOYMENT' WHERE room_id=$room_id");
							$enter_game_loop->execute();
							$enter_game_loop->closeCursor();
							
							// Reset turn
							$reset_turn = $dbh->prepare("UPDATE session SET turn=0");
							$reset_turn->execute();
							$reset_turn->closeCursor();
							
							$reset_turn = $dbh->prepare("UPDATE session SET turn=1 WHERE turn_seq=1");
							$reset_turn->execute();
							$reset_turn->closeCursor();
						}
					}	
				}	
			}
			
			$respond = respond_regular_info($database_path, "PLAYER $current_turn_player_session_key IS DEPLOYING - deploy_on=[A PLACE NAME]");
			echo json_encode($respond);
		}
		
		// During post deployment status
		if ($game_status['status'] == "POST_DEPLOYMENT") {
			
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			// Check if AI flag turn on
			$AI_flag = get_AI_flag($database_path, $current_turn_player_session_key);
			
			if ($_COOKIE["session_key"] == $current_turn_player_session_key && $_GET["reinforce"] != '' || $AI_flag != "0") {
				if ($AI_flag != "0") { 
					if ($AI_flag == "1")
						$toponym = $random_AI->post_deployment($current_turn_player_session_key);
					
					reinforcement_for_current_player($database_path, 5, $toponym);
					
					// Update turn
					update_to_next_player_turn($database_path);
				}
				else {
					$reinforce_to = $_GET["reinforce"];
					$get_reinforce_to_owner = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$reinforce_to'");
					$get_reinforce_to_owner->execute();
					$result = $get_reinforce_to_owner->fetch(PDO::FETCH_ASSOC);
					$reinforce_to_owner = $result['owner'];
					$get_reinforce_to_owner->closeCursor();
					
					if ($reinforce_to_owner == $current_turn_player_session_key) {
						reinforcement_for_current_player($database_path, 5, $_GET["reinforce"]);
						// Update turn
						update_to_next_player_turn($database_path);
					}
				}
				
			}
			
			// End post deployment if all troops left for each player is equal to 0
			$get_still_deploying_user = $dbh->prepare("SELECT COUNT(*) FROM session WHERE NOT troops_left=0");
			$get_still_deploying_user->execute();
			$result = $get_still_deploying_user->fetch(PDO::FETCH_ASSOC);
			$still_deploying_user = $result['COUNT(*)'];
			$get_still_deploying_user->closeCursor();
			if ($still_deploying_user == 0) {
				// Update game status to ENGAGEMENT_PLANNING
				$update_game_status = $dbh->prepare("UPDATE game_room SET status='ENGAGEMENT_PLANNING' WHERE room_id=$room_id");
				$update_game_status->execute();
				$update_game_status->closeCursor();
				
				// Auto refill for player 1
				refill_troops_for_current_player($database_path);
				
				// Set refill flag to 0
				$update_refill_flag = $dbh->prepare("UPDATE session SET refill_troops=1 WHERE turn_seq=1");
				$update_refill_flag->execute();
				$update_refill_flag->closeCursor();
				
				// Get refill flag for current player
				$get_refill_flag = $dbh->prepare("SELECT refill_troops FROM session WHERE session_key=$current_turn_player_session_key");
				$get_refill_flag->execute();
				$result = $get_refill_flag->fetch(PDO::FETCH_ASSOC);
				$refill_flag = $result['refill_troops'];
				$get_refill_flag->closeCursor();
				
				if ($refill_flag == 1) {
					// Refill troops
					refill_troops_for_current_player($database_path);
					
					// Set refill flag to 0
					$set_refill_flag = $dbh->prepare("UPDATE session SET refill_troops=0 WHERE session_key=$current_turn_player_session_key");
					$set_refill_flag->execute();
					$set_refill_flag->closeCursor();
				}
			}
			
			$respond = respond_regular_info($database_path, "PLAYER $current_turn_player_session_key IS REINFORCING IN POST_DEPLOYMENT STAGE - reinforce=[A PLACE NAME]");
			echo json_encode($respond);
		}
		
		// During engagment planning status
		if ($game_status['status'] == "ENGAGEMENT_PLANNING") {
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			// Check if AI flag turn on
			$AI_flag = get_AI_flag($database_path, $current_turn_player_session_key);
			
			if ($_COOKIE["session_key"] == $current_turn_player_session_key || $AI_flag != "0") {
				
				// Check reinforcement
				if ($AI_flag != "0") {
					$get_total_refill_troops =$dbh->prepare("SELECT troops_left FROM session WHERE session_key=$current_turn_player_session_key");
					$get_total_refill_troops->execute();
					$result = $get_total_refill_troops->fetch(PDO::FETCH_ASSOC);
					$total_refill_troops = $result['troops_left'];
					$get_total_refill_troops->closeCursor();
					
					if ($AI_flag == "1")
						$chosen_land_array = $random_AI->engagement_planning($current_turn_player_session_key, $continents, $total_refill_troops);
					
					foreach ($chosen_land_array as $toponym) {
						reinforcement_for_current_player($database_path, 1, $toponym);
					}
				}
				else {
					$reinforce_to = $_GET["reinforce"];
					$get_reinforce_to_owner = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$reinforce_to'");
					$get_reinforce_to_owner->execute();
					$result = $get_reinforce_to_owner->fetch(PDO::FETCH_ASSOC);
					$reinforce_to_owner = $result['owner'];
					$get_reinforce_to_owner->closeCursor();
					
					if ($reinforce_to_owner == $current_turn_player_session_key) {
						reinforcement_for_current_player($database_path, 1, $_GET["reinforce"]);
					}
				}
				
				// Check using card
				$backup_troops = check_using_card($database_path);
				if ($backup_troops > 0) {
					// User using card, give them extra troops
					update_troops_number($database_path, $backup_troops);
				}
				
				// Change to ENGAGEMENT_ATTACK stage if user has no troops for deployment
				$get_troops_left = $dbh->prepare("SELECT troops_left FROM session WHERE session_key=$current_turn_player_session_key");
				$get_troops_left->execute();
				$result = $get_troops_left->fetch(PDO::FETCH_ASSOC);
				$troops_left = $result['troops_left'];
				$get_troops_left->closeCursor();
				if ($troops_left <= 0) {
					// Update gain_card_flag
					$set_gain_card_flag = $dbh->prepare("UPDATE session SET gain_card_flag=1 WHERE session_key=$current_turn_player_session_key");
					$set_gain_card_flag->execute();
					$set_gain_card_flag->closeCursor();
					
					$set_stage = $dbh->prepare("UPDATE game_room SET status='ENGAGEMENT_ATTACK' WHERE room_id=$room_id");
					$set_stage->execute();
					$set_stage->closeCursor();
				}
			}
			
			$respond = respond_regular_info($database_path, "PLAYER $current_turn_player_session_key IS PLANNING TROOPS IN ENGAGMENT_PLANNING STAGE - reinforce=[A PLACE NAME], user can use card in this stage by suppling use_card=1&[card_1,card_2,card_3]=[A PLACE NAME]&[card_1_type,card_2_type,card_3_type]=[A TROOP TYPE]");
			echo json_encode($respond);
		}
		
		// During engagment attack status
		if ($game_status['status'] == "ENGAGEMENT_ATTACK") {
			$war_result = array();
			
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			$set_watch_battle_flag = $dbh->prepare("UPDATE session SET watch_battle_flag=0 WHERE session_key=" . $_COOKIE['session_key']);
			$set_watch_battle_flag->execute();
			$set_watch_battle_flag->closeCursor();
			
			// Check if AI flag turn on
			$AI_flag = get_AI_flag($database_path, $current_turn_player_session_key);
			
			if ($_COOKIE["session_key"] == $current_turn_player_session_key && $battle_flag_count == 0 || $AI_flag != "0") {
				// End the stage
				if ($_GET['end_attack'] == "1" || $AI_flag != "0" && $random_AI->engagement_attack($current_turn_player_session_key) == "No") {
					// Update stage
					$update_stage = $dbh->prepare("UPDATE game_room SET status='ENGAGEMENT_MOBILIZE' WHERE room_id=1");
					$update_stage->execute();
					$update_stage->closeCursor();
					
					// Clear all flag
					$clear_all_flag = $dbh->prepare("UPDATE map_status SET battle_flag=0, identity=0");
					$clear_all_flag->execute();
					$clear_all_flag->closeCursor();
				}
				else if ($_GET['end_mobilize'] == "1") {
					// Clear all flag
					$clear_all_flag = $dbh->prepare("UPDATE map_status SET battle_flag=0, identity=0");
					$clear_all_flag->execute();
					$clear_all_flag->closeCursor();
				}
				// Get a land and mobilize troops
				else if ($_GET['from'] != '' && $_GET['to'] != '' && $_GET['status'] == 'mobilize') {
					$get_from_identity = $dbh->prepare("SELECT toponym FROM map_status WHERE battle_flag=2 AND identity=1");
					$get_from_identity->execute();
					$result = $get_from_identity->fetch(PDO::FETCH_ASSOC);
					$from_toponym = $result['toponym'];
					$get_from_identity->closeCursor();
					
					$get_to_identity = $dbh->prepare("SELECT toponym FROM map_status WHERE battle_flag=2 AND identity=2");
					$get_to_identity->execute();
					$result = $get_to_identity->fetch(PDO::FETCH_ASSOC);
					$to_toponym = $result['toponym'];
					$get_to_identity->closeCursor();
					
					// Move troops
					$unit = 1;
					$mobilize_from = $_GET['from'];
					$mobilize_to = $_GET['to'];
					
					if ($to_toponym == $mobilize_to && $from_toponym == $mobilize_from)
						mobilize($database_path, $mobilize_from, $mobilize_to, $unit);
				}
				// Attack other
				else if ($_GET['from'] != '' && $_GET['to'] != ''&& $_GET['status'] == 'attack' || $AI_flag != "0") {
					$attack_from;
					$attack_to;
					if ($AI_flag != "0") {
						$result;
						if ($AI_flag == "1")
								$result = $random_AI->engagement_attack($current_turn_player_session_key);
						
						list($attack_from, $attack_to) = explode(",", $result);
						
						/*if (!($fp = fopen('mylog.txt', 'a'))) {
							die('Cannot open log file');
						}
						fwrite($fp, "$current_turn_player_session_key	: $attack_from	:	$attack_to\n");*/
					}
					else {
						$attack_from	= $_GET['from'];
						$attack_to		= $_GET['to'];
					}
					
					$array_of_neighbour = get_neighbour_toponyms($attack_from);
					$neighbour_flag = 0;
					foreach ($array_of_neighbour as $neighbour) {
						if ($neighbour == $attack_to) {
							$neighbour_flag = 1;
						}
					}
					
					$attack_from_owner = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$attack_from'");
					$attack_from_owner->execute();
					$result = $attack_from_owner->fetch(PDO::FETCH_ASSOC);
					$attacker_session = $result['owner'];
					$attack_from_owner->closeCursor();
					
					$attack_to_owner = $dbh->prepare("SELECT owner FROM map_status WHERE toponym='$attack_to'");
					$attack_to_owner->execute();
					$result = $attack_to_owner->fetch(PDO::FETCH_ASSOC);
					$defender_session = $result['owner'];
					$attack_to_owner->closeCursor();

					if ($neighbour_flag == 1 && $attacker_session == $current_turn_player_session_key && $defender_session != $current_turn_player_session_key) {
						// Get attacker max dices 
						$get_attacker_troops = $dbh->prepare("SELECT troops, owner FROM map_status WHERE toponym='$attack_from'");
						$get_attacker_troops->execute();
						$result = $get_attacker_troops->fetch(PDO::FETCH_ASSOC);
						$attacker_troops = $result['troops'];
						$attacker_session = $result['owner'];
						$get_attacker_troops->closeCursor();
						
						// Get defender max dices
						$get_defender_troops = $dbh->prepare("SELECT troops, owner FROM map_status WHERE toponym='$attack_to'");
						$get_defender_troops->execute();
						$result = $get_defender_troops->fetch(PDO::FETCH_ASSOC);
						$defender_troops = $result['troops'];
						$defender_session = $result['owner'];
						$get_defender_troops->closeCursor();
						
						if ($attacker_troops > 1 && $defender_troops > 0) {
							// Clear all battle flag = 1
							$clear_flag_1 = $dbh->prepare("UPDATE map_status SET battle_flag=0, identity=0 WHERE battle_flag=1");
							$clear_flag_1->execute();
							$clear_flag_1->closeCursor();
							
							// Set battle flag
							$set_battle_flag = $dbh->prepare("UPDATE map_status SET battle_flag=1 WHERE toponym='$attack_from' OR toponym='$attack_to'");
							$set_battle_flag->execute();
							$set_battle_flag->closeCursor();
							
							$set_attacker_identity = $dbh->prepare("UPDATE map_status SET identity=1 WHERE toponym='$attack_from'");
							$set_attacker_identity->execute();
							$set_attacker_identity->closeCursor();
							
							$set_defender_identity = $dbh->prepare("UPDATE map_status SET identity=2 WHERE toponym='$attack_to'");
							$set_defender_identity->execute();
							$set_defender_identity->closeCursor();
							
							$set_watch_battle_flag = $dbh->prepare("UPDATE session SET watch_battle_flag=1 WHERE NOT session_key=$current_turn_player_session_key AND NOT ai_flag=1");
							$set_watch_battle_flag->execute();
							$set_watch_battle_flag->closeCursor();
							
							// Roll the dices
							$attacker_max_dices = $attacker_troops;
							$defender_max_dices = $defender_troops;
							
							if ($attacker_troops > 3) {
								$attacker_max_dices = 3;
							}
							else if ($attacker_troops == 3) {
								$attacker_max_dices = 2;
							}
							else if ($attacker_troops == 2) {
								$attacker_max_dices = 1;
							}
							
							if ($defender_troops > 2) {
								$defender_max_dices = 2;
							}
							
							$attacker_dices_seq = array();
							$defender_dices_seq = array();
							
							for ($i = 0; $i < $attacker_max_dices; $i++) {
								$attacker_dices_seq[$i] = rand(1, 6);
							}
							for ($i = 0; $i < $defender_max_dices; $i++) {
								$defender_dices_seq[$i] = rand(1, 6);
							}
							
							sort($attacker_dices_seq);
							sort($defender_dices_seq);
							
							$attacker_lost = 0;
							$defender_lost = 0;
							
							$max_dices;
							if ($defender_max_dices < $attacker_max_dices)
								$max_dices = $defender_max_dices;
							else
								$max_dices = $attacker_max_dices;
							
							for ($i = 0; $i < $max_dices; $i++) {
								$defender_dice = (int)array_pop($defender_dices_seq);
								$attacker_dice = (int)array_pop($attacker_dices_seq);
								
								if($defender_dice >= $attacker_dice) {
									$attacker_lost += 1;
								}
								else {
									$defender_lost += 1;
								}
							}
							
							(int)$attacker_troops -= (int)$attacker_lost;
							(int)$defender_troops -= (int)$defender_lost;
							
							if ($defender_troops < 0) {
								$defender_troops = 0;
							}
							
							$set_attacker_lost = $dbh->prepare("UPDATE map_status SET troops=$attacker_troops WHERE toponym='$attack_from'");
							$set_attacker_lost->execute();
							$set_attacker_lost->closeCursor();
							
							$set_defender_lost = $dbh->prepare("UPDATE map_status SET troops=$defender_troops WHERE toponym='$attack_to'");
							$set_defender_lost->execute();
							$set_defender_lost->closeCursor();
													
							// Update total troops
							$get_attacker_total_troops = $dbh->prepare("SELECT troops FROM session WHERE session_key=$attacker_session");
							$get_attacker_total_troops->execute();
							$result = $get_attacker_total_troops->fetch(PDO::FETCH_ASSOC);
							$attacker_total_troops = $result['troops'];
							$get_attacker_total_troops->closeCursor();
							
							$get_defender_total_troops = $dbh->prepare("SELECT troops FROM session WHERE session_key=$defender_session");
							$get_defender_total_troops->execute();
							$result = $get_defender_total_troops->fetch(PDO::FETCH_ASSOC);
							$defender_total_troops = $result['troops'];
							$get_defender_total_troops->closeCursor();
							
							$attacker_total_troops -= $attacker_lost;
							$defender_total_troops -= $defender_lost;
							
							$set_attacker_total_lost = $dbh->prepare("UPDATE session SET troops=$attacker_total_troops WHERE session_key=$attacker_session");
							$set_attacker_total_lost->execute();
							$set_attacker_total_lost->closeCursor();
							
							$set_defender_total_lost = $dbh->prepare("UPDATE session SET troops=$defender_total_troops WHERE session_key=$defender_session");
							$set_defender_total_lost->execute();
							$set_defender_total_lost->closeCursor();
							
							// Actual dices respond
							$war_result['from_dices'] = $attacker_dices_seq;
							$war_result['from_lost'] = $attacker_lost;
							$war_result['from_dices'] = $defender_dices_seq;
							$war_result['to_dices'] = $defender_lost;
							
							// If defender lose all troops
							if ($defender_troops <= 0) {
								// Update owner
								$set_owner = $dbh->prepare("UPDATE map_status SET owner=$current_turn_player_session_key WHERE toponym='$attack_to'");
								$set_owner->execute();
								$set_owner->closeCursor();
								
								// Set battle flag
								$set_battle_flag = $dbh->prepare("UPDATE map_status SET battle_flag=2 WHERE toponym='$attack_from' OR toponym='$attack_to'");
								$set_battle_flag->execute();
								$set_battle_flag->closeCursor();
								
								
								mobilize($database_path, $attack_from, $attack_to, $attacker_max_dices);
								
								// Attacker gain 1 card;
								$get_gain_card_flag = $dbh->prepare("SELECT gain_card_flag FROM session WHERE session_key=$current_turn_player_session_key");
								$get_gain_card_flag->execute();
								$result = $get_gain_card_flag->fetch(PDO::FETCH_ASSOC);
								$gain_card_flag = $result['gain_card_flag'];
								$get_gain_card_flag->closeCursor();
								if ($gain_card_flag == "1") {
									gain_one_card($database_path, $attacker_session, $continents);
									
									// Update gain_card_flag
									$set_gain_card_flag = $dbh->prepare("UPDATE session SET gain_card_flag=0 WHERE session_key=$current_turn_player_session_key");
									$set_gain_card_flag->execute();
									$set_gain_card_flag->closeCursor();
								}
									
								
								// Check if any player lose
								$get_loser = $dbh->prepare("SELECT session_key FROM session WHERE troops<=0 AND NOT turn_seq=-1");
								$get_loser->execute();
								$result = $get_loser->fetch(PDO::FETCH_ASSOC);
								$loser_session_key = $result['session_key'];
								$get_loser->closeCursor();
								// End of checking
								
								// Do something if there are players lose the game
								if ($loser_session_key != '') {
									
									// Pull it out of turn sequence
									$remove_player_turn = $dbh->prepare("UPDATE session SET turn_seq=-1 WHERE session_key=$loser_session_key");
									$remove_player_turn->execute();
									$remove_player_turn->closeCursor();
									
									// Transfer all card to the one who conquer it
									$get_loser_card = $dbh->prepare("SELECT card_number FROM session WHERE session_key=$loser_session_key");
									$get_loser_card->execute();
									$result = $get_loser_card->fetch(PDO::FETCH_ASSOC);
									$loser_card_number = $result['card_number'];
									$get_loser_card->closeCursor();
									
									$get_winnder_card = $dbh->prepare("SELECT card_number FROM session WHERE session_key=$attacker_session");
									$get_winnder_card->execute();
									$result = $get_winnder_card->fetch(PDO::FETCH_ASSOC);
									$winner_card_number = $result['card_number'];
									$get_winnder_card->closeCursor();
									
									$winner_card_number += $loser_card_number;
									
									$set_winner_card_number = $dbh->prepare("UPDATE session SET card_number=$winner_card_number WHERE session_key=$attacker_session");
									$set_winner_card_number->execute();
									$set_winner_card_number->closeCursor();
									
									$set_winner_card = $dbh->prepare("UPDATE card_status SET owner=$attacker_session WHERE owner=$loser_session_key");
									$set_winner_card->execute();
									$set_winner_card->closeCursor();
								}
							}					
						}
					}
				}
			}
			
			// Check winning condition
			$get_number_of_player_left = $dbh->prepare("SELECT COUNT(DISTINCT owner) FROM map_status");
			$get_number_of_player_left->execute();
			$result = $get_number_of_player_left->fetch(PDO::FETCH_ASSOC);
			$number_of_player_left = $result['COUNT(DISTINCT owner)'];
			$get_number_of_player_left->closeCursor();
			if ($number_of_player_left <= 1) {
				// The only left player win!!!
				
				// Update the game status
				$end_game = $dbh->prepare("UPDATE game_room SET status='END' WHERE room_id=$room_id");
				$end_game->execute();
				$end_game->closeCursor();
				
				// Wrap up
				/***** Do it at last *****/
				//wrap_up($database_path);
			}
			// End of winning condition
			
			$respond = respond_regular_info($database_path, "PLAYER $current_turn_player_session_key IS ATTACKING IN STAGE ENGAGEMENT_ATTACK - status=[attack/mobilize]&from=[A PLACE NAME]&to=[A PLACE NAME], end_attack=1(END ATTACK TURN), end_mobilize=1(END MOBILIZING AFTER CONQUER A PLACE)");
			
			// Actual war info respond
			$get_attacker = $dbh->prepare("SELECT owner, toponym FROM map_status WHERE battle_flag=1 AND identity=1");
			$get_attacker->execute();
			$result = $get_attacker->fetch(PDO::FETCH_ASSOC);
			$attacker = $result['owner'];
			$attack_from = $result['toponym'];
			$get_attacker->closeCursor();
			
			$get_defender = $dbh->prepare("SELECT owner, toponym FROM map_status WHERE battle_flag=1 AND identity=2");
			$get_defender->execute();
			$result = $get_defender->fetch(PDO::FETCH_ASSOC);
			$defender = $result['owner'];
			$attack_to = $result['toponym'];
			$get_defender->closeCursor();
			
			$respond['war'] = array();
			$respond['war']['from_player'] = $attacker;
			$respond['war']['from_location'] = $attack_from;
			$respond['war']['to_player'] = $defender;
			$respond['war']['to_location'] = $attack_to;
			
			if (count($war_result) != 0) {
				$respond['war']['from_dices'] = $war_result['from_dices'];
				$respond['war']['from_lost'] = $war_result['from_lost'];
				$respond['war']['to_dices'] = $war_result['from_dices'];
				$respond['war']['to_lost'] = $war_result['to_dices'];
			}
			
			echo json_encode($respond);
		}
		
		// During engagment mobilize status
		if ($game_status['status'] == "ENGAGEMENT_MOBILIZE") {
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			$AI_flag = get_AI_flag($database_path, $current_turn_player_session_key);
			
			if ($_COOKIE["session_key"] == $current_turn_player_session_key || $AI_flag != "0") {
				if ($_GET['from'] != '' && $_GET['to'] != '' && $_GET['units'] != '') {
					// Mobilize troops
					$unit = $_GET['units'];
					$mobilize_from = $_GET['from'];
					$mobilize_to = $_GET['to'];
					
					mobilize($database_path, $mobilize_from, $mobilize_to, $unit);
				}
				else if ($_GET['end_mobilize'] == "1" || $AI_flag != "0") {
					// Set refill flag
					$set_refill_flag = $dbh->prepare("UPDATE session SET refill_troops=1");
					$set_refill_flag->execute();
					$set_refill_flag->closeCursor();
					
					// Update the game status
					$set_to_planning = $dbh->prepare("UPDATE game_room SET status='ENGAGEMENT_PLANNING' WHERE room_id=$room_id");
					$set_to_planning->execute();
					$set_to_planning->closeCursor();
					
					// Set refill flag to 1
					$update_refill_flag = $dbh->prepare("UPDATE session SET refill_troops=1");
					$update_refill_flag->execute();
					$update_refill_flag->closeCursor();
					
					// Update to next player turn
					update_to_next_player_turn($database_path);
					
					// Get refill flag for current player
					$get_refill_flag = $dbh->prepare("SELECT refill_troops FROM session WHERE session_key=$current_turn_player_session_key");
					$get_refill_flag->execute();
					$result = $get_refill_flag->fetch(PDO::FETCH_ASSOC);
					$refill_flag = $result['refill_troops'];
					$get_refill_flag->closeCursor();
					
					if ($refill_flag == 1) {
						// Refill troops
						refill_troops_for_current_player($database_path);
						
						// Set refill flag to 0
						$set_refill_flag = $dbh->prepare("UPDATE session SET refill_troops=0 WHERE session_key=$current_turn_player_session_key");
						$set_refill_flag->execute();
						$set_refill_flag->closeCursor();
					}
				}
			}
			
			
			
			$respond = respond_regular_info($database_path, "PLAYER $current_turn_player_session_key IS MOBILIZING IN STAGE ENGAGEMENT_MOBILIZE");
			echo json_encode($respond);
		}
		
		// During wait for using card status 
		if ($game_status['status'] == "WAIT_FOR_USING_CARD") {
			$current_turn_player_session_key = get_current_turn_player_session($database_path);
			
			$AI_flag = get_AI_flag($database_path, $current_turn_player_session_key);
			
			if ($_COOKIE["session_key"] == $current_turn_player_session_key || $AI_flag != "0") {
				$backup_troops = check_using_card();
				
				if ($AI_flag != "0") {
					$get_troops_left_for_reinforcement = $dbh->prepare("SELECT troops_left FROM session WHERE session_key=$current_turn_player_session_key");
					$get_troops_left_for_reinforcement->execute();
					$result = $get_troops_left_for_reinforcement->fetch(PDO::FETCH_ASSOC);
					$troops_left = $result['troops_left'];
					$get_troops_left_for_reinforcement->closeCursor();
					
					for ($i = 0; $i < $troops_left; $i++) {
						if ($AI_flag == "1")
							$toponym = $random_AI->post_deployment($current_turn_player_session_key);
						
						reinforcement_for_current_player($database_path, 1, $toponym);
					}
				}
				
				if($backup_troops > 0) {
					// User using card, give them extra troops
					update_troops_number($database_path, $backup_troops);
				}
				
				// Check reinforcement
				if ($_GET['reinforce'] != '') {
					reinforcement_for_current_player($database_path, 1, $_GET['reinforce']);
				}
				
				// Check max card
				$get_max_card = $dbh->prepare("SELECT COUNT(*) FROM card_statud WHERE owner=$current_turn_player_session_key");
				$get_max_card->execute();
				$result = $get_max_card->fetch(PDO::FETCH_ASSOC);
				$max_card = $result['COUNT(*)'];
				$get_max_card->closeCursor();
				
				// Check troops left for reinforcement
				$get_troops_left = $dbh->prepare("SELECT troops_left FROM session WHERE session_key=$current_turn_player_session_key");
				$get_troops_left->execute();
				$result = $get_troops_left->fetch(PDO::FETCH_ASSOC);
				$troops_left = $result['COUNT(*)'];
				$get_troops_left->closeCursor();
				
				if ($max_card < 5 && $troops_left == 0) {
					$reset_battle_flag = $dbh->prepare("UPDATE session SET battle_flag=0, identity=0");
					$reset_battle_flag->execute();
					$reset_battle_flag->closeCursor();	
					
					// Change it to other status
					$set_to_attack = $dbh->prepare("UPDATE game_room SET status='ENGAGEMENT_ATTACK' WHERE room_id=$room_id");
					$set_to_attack->execute();
					$set_to_attack->closeCursor();	
				}
			}
			
			$respond = respond_regular_info($database_path, "user can use card in this stage by suppling use_card=1&[card_1,card_2,card_3]=[A PLACE NAME]&[card_1_type,card_2_type,card_3_type]=[A TROOP TYPE] |||||||| reinforce=[A PLACE NAME] for reinforcement, change to ENGAGEMENT_ATTACK if current user is holding less than 5 cards AND no troops left for reinforcment");
			echo json_encode($respond);
		}
	}
	catch (PDOException $e) {
		echo $e->getMessage();
	}
	
	// Debug console
	if ($_GET['view'] == 1) {
		echo "\nYou are ".$_COOKIE['session_key']."(Session key value)";
		echo "\nAll sessions\n=============================\n";
		if ($dbh != NULL) {
			$query = "SELECT * FROM session";
			foreach ($dbh->query($query) as $row) {
				print 'session_key: ' . $row['session_key'] . "\t";
				print 'username: ' . $row['username'] . "\t";
				print 'turn: ' . $row['turn'] . "\t";
				print 'turn_seq: ' . $row['turn_seq'] . "\t";
				print 'ready: ' . $row['ready'] . "\t";
				print 'troops: ' . $row['troops'] . "\t";
				print 'troops_left: ' . $row['troops_left'] . "\t";
				print 'refill_troops: ' . $row['refill_troops'] . "\t";
				print 'watch_battle_flag: ' . $row['watch_battle_flag'] . "\t";
				print 'ai_flag: ' . $row['ai_flag'] . "\t";
				print 'card_number: ' . $row['card_number'] . "\t";
				print 'last_respond: ' . $row['last_respond'] . "\n";
			}	
		}
		else
			echo "NULL dbh";
		
		echo "\nMap status\n=============================\n";
		if ($dbh != NULL) {
			$query = "SELECT * FROM map_status";
			foreach ($dbh->query($query) as $row) {
				print 'toponym: ' . $row['toponym'] . "\t";
				print 'continent: ' . $row['continent'] . "\t";
				print 'owner: ' . $row['owner'] . "\t";
				print 'troops: ' . $row['troops'] . "\t";
				print 'battle_flag: ' . $row['battle_flag'] . "\t";
				print 'identity: ' . $row['identity'] . "\n";
		    }
		}
		else
			echo "NULL dbh";
		
		echo "\nGame room status\n=============================\n";
		if ($dbh != NULL) {
			$query = "SELECT * FROM game_room";
			foreach ($dbh->query($query) as $row) {
		        print 'room_id: ' . $row['room_id'] . "\t";
		        print 'room_name: ' . $row['room_name'] . "\t";
		        print 'start_time: ' . $row['start_time'] . "\t";
		        print 'place_left: ' . $row['place_left'] . "\t";
				print 'backup_round: ' . $row['backup_round'] . "\t";
		        print 'status: ' . $row['status'] . "\n";
		    }	
		}
		else
			echo "NULL dbh";
		
		echo "\nCard status\n=============================\n";
		if ($dbh != NULL) {
			$query = "SELECT * FROM card_status";
			foreach ($dbh->query($query) as $row) {
		        print 'owner: ' . $row['owner'] . "\t";
		        print 'toponym: ' . $row['toponym'] . "\t";
		        print 'troop_type: ' . $row['troop_type'] . "\n";
		    }	
		}
		else
			echo "NULL dbh";
	}
	?>
